package com.example.bluetooth_test;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.print.PrinterId;
import android.text.method.NumberKeyListener;

import java.io.IOException;
import java.util.UUID;

public class ServerThread extends Thread {

    private static final String NAME = "Bluetooth_STM32";
    private static final UUID MY_UUID = UUID.fromString(Constant.UUID);
    private BluetoothServerSocket mServerSocket;
    private final Handler handler;
    private final BluetoothAdapter bluetoothAdapter;
    private ConnectedThread nConnectedThread;

    public ServerThread(Handler handler, BluetoothAdapter bluetoothAdapter) {
        this.handler = handler;
        this.bluetoothAdapter = bluetoothAdapter;

        BluetoothServerSocket tmp = null;
        try {
            tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME,MY_UUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mServerSocket = tmp;
    }

    public void run(){

        BluetoothSocket mSocket;
        //持续监听，直到出现异常
        while (true){
            try {
                handler.sendMessage(handler.obtainMessage(Constant.STATE_LISTENING));
                //从队列中取出一个链接，如果没有则等待
                mSocket = mServerSocket.accept();
            } catch (IOException e) {
                e.printStackTrace();
                handler.sendMessage(handler.obtainMessage(Constant.STATE_CONNECTION_FAILED));
                break;
            }

            //如果有一个链接被接受
            if (mSocket != null){
                //在单独的线程完成管理连接的工作
                manageConnectedSocket(mSocket);
                //与客户通讯结束后,结束socket
                try {
                    mServerSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }

    private void manageConnectedSocket(BluetoothSocket socket){
        //只支持同时处理一个链接，如果有链接，则取消
        //数据处理
        if (nConnectedThread != null) {
            nConnectedThread.cancel();
        }
        handler.sendMessage(handler.obtainMessage(Constant.STATE_A_CLIENT));
        nConnectedThread = new ConnectedThread(socket, handler);
        nConnectedThread.start();
    }

    public void cancle() {
        try {
            mServerSocket.close();
            handler.sendEmptyMessage(Constant.STATE_FINISH_LISTENINHG);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void sendData(byte[] bytes) {
        if (nConnectedThread != null) {
            nConnectedThread.write(bytes);
        }
    }
}



